const app = getApp()
import Dialog from '@vant/weapp/dialog/dialog';
import {
    showMsg
} from '../../../../utils/config.js'
import {
    reqDeviceUserpage,
    reqProductList,
    reqDeviceUserunBind,
    reqGetDeviceByImei,
    reqDeviceUserbind
} from '../../../../request/api'
Page({
    data: {
        navHeight: app.globalData.navHeight + 'px', //头部距离
        bottomHeight: app.globalData.bottomHeight + 'px', //iphone底部距离

        dataList: [], //设备列表
        page: 1,
        isNextPage: true,
        triggered: false,
        searchValue: '',

        // 筛选弹窗开始
        showSearch: false, //筛选弹窗
        statusList: [{
            id: '',
            name: '全部',
            active: true,
        }, {
            id: 1,
            name: '在线',
            active: false,
        }, {
            id: 0,
            name: '离线',
            active: false,
        }, ],
        online: '', //选中的设备状态 
        productList: [],
        isAlarmList: [{
            active: false,
            name: "正常",
            id: 0
        }, {
            active: false,
            name: "告警",
            id: 1
        }],
        isAlarm: "",
        productId: '', //选中的产品
        hasSearch: false, //是否有筛选
        minBattery: "", //最小值
        maxBattery: "", //最大值
        // 筛选弹窗结束

        formData: [],
        showDatePicker: false,
        currentDate: '12:00',
        deviceImei: "",
        deviceStr: {}
    },

    onLoad() {
        this.getProductList()
    },
    onShow() {
        this.getInitDataList() //最初状态
    },

    // 获取设备imei
    imeiChange(e) {
        let {
            value
        } = e.detail
        this.setData({
            deviceImei: value
        })
        if (value.length >= 3) {
            this.getDeviceByImei(value)
        }
        if (value.length <= 0) {
            // 删除到没有时，清除
            this.setData({
                deviceStr: {}
            })
        }
    },
    // 判断imei是否已存在
    async getDeviceByImei(imei) {
        const res = await reqGetDeviceByImei(imei)
        if (res.code !== 20000) {
            showMsg('设备不存在')
            return
        }
        console.log(res);
        let {
            row
        } = res.data
        this.data.productList.forEach(citem => {
            if (row.deviceType === citem.deviceType) {
                row.type = citem.name //产品类型
            }
        })
        this.setData({
            deviceStr: row
        })
    },
    // 确认新增
    async confirm() {
        const reste = await reqGetDeviceByImei(this.data.deviceImei)
        if (reste.code !== 20000) {
            showMsg('设备不存在')
            return
        }
        const res = await reqDeviceUserbind({
            userId: app.globalData.userId,
            imei: this.data.deviceImei
        })
        if (res.code != 20000) return showMsg(res.message);
        console.log(res);
        showMsg("绑定成功", "success")
        setTimeout(() => {
            this.closeSpace()
            this.getInitDataList()
            this.setData({
                deviceImei: "",
                deviceStr: {}
            })
        }, 1000)
    },
    // 产品列表
    async getProductList() {
        const res = await reqProductList()
        if (res.code !== 20000) return showMsg(res.message)
        let {
            rows
        } = res.data
        rows.unshift({
            id: '',
            name: '全部',
            active: true
        })

        this.setData({
            productList: rows
        })
    },
    /**
     * @name: 获取设备列表
     */
    async getDataList() {
        let params = {
            userId: app.globalData.userId,
            imei: this.data.searchValue
        }
        const res = await reqDeviceUserpage(this.data.page, 10, params)
        if (res.code !== 20000) return showMsg(res.message)
        let {
            rows
        } = res.data
        let {
            productList
        } = this.data
        if (rows && rows.length) {
            rows.forEach(item => {
                productList.forEach(citem => {
                    if (item.deviceType === citem.deviceType) {
                        item.type = citem.name //产品类型
                        item.pic = citem.pic
                    }
                })
            });
        }
        if (this.data.page === 1) {
            this.setData({
                dataList: rows,
                isNextPage: true
            })
        } else if (this.data.page > 1 && rows.length) {
            this.setData({
                dataList: this.data.dataList.concat(rows),
                isNextPage: true
            })
        } else if (this.data.page > 1 && !rows.length) {
            showMsg('已经到底啦~')
            this.setData({
                isNextPage: false
            })
        }
    },
    // 滚动到底部触发
    lower() {
        if (!this.data.isNextPage) return
        this.setData({
            page: this.data.page + 1,
        })
        this.getDataList()
    },
    // 下拉刷新
    async onRefresh() {
        this.setData({
            // dataList: [],
            page: 1,
            isNextPage: true,
            triggered: true,
        })
        await this.getDataList()
        this.setData({
            triggered: false,
        })
    },
    // 操作列表后回到最初状态
    getInitDataList() {
        this.setData({
            page: 1,
            isNextPage: true,
            // dataList: []
        })
        this.getDataList()
    },

    // 输入框搜索
    searchChange(e) {
        // e.detail = e.detail.replace(/[^0-9]/g, '');
        e.detail = e.detail.replace(/[\u4e00-\u9fa5]/g, '');
        console.log(e.detail);
        // 防止输入字母也触发接口调用
        if (this.data.searchValue2 == e.detail) {
            this.setData({
                searchValue: e.detail,
                searchValue2: e.detail,
            })
            return;
        }
        this.setData({
            searchValue: e.detail,
            searchValue2: e.detail,
        })
        clearTimeout(this.data.timer)
        this.data.timer = setTimeout(() => {
            this.getInitDataList()
        }, 500)
    },
    // js判断字符串是否为JSON格式
    isjson(str) {
        if (typeof str == 'string') {
            try {
                var obj = JSON.parse(str);
                if (typeof obj == 'object' && obj) {
                    return true;
                } else {
                    return false;
                }

            } catch (e) {
                console.log('error：' + str + '!!!' + e);
                return false;
            }
        }
        console.log('It is not a string!')
    },
    // 点击扫码获取imei
    imeiScan() {
        const that = this
        let qrcode = ''
        wx.scanCode({
            success(res) {
                qrcode = res.result;
                if (!qrcode) return showMsg('扫描失败，请重新扫描')
                if (qrcode.length >= 3) {
                    if (that.isjson(qrcode)) {
                        const result = JSON.parse(qrcode);
                        // JSON字符格式
                        that.setData({
                            searchValue: result.ID, //威视达康摄像机取值，后续看需求更改 lc
                        })
                        clearTimeout(that.data.timer)
                        that.data.timer = setTimeout(() => {
                            that.getInitDataList()
                        }, 500)
                    } else {
                        // 非JSON格式
                        that.setData({
                            searchValue: qrcode,
                        })
                        clearTimeout(that.data.timer)
                        that.data.timer = setTimeout(() => {
                            that.getInitDataList()
                        }, 500)
                    }
                } else {
                    showMsg('扫描失败，请重新扫描')
                    return
                }
            }
        })
    },
    // js判断字符串是否为JSON格式
    isjson(str) {
        if (typeof str == 'string') {
            try {
                var obj = JSON.parse(str);
                if (typeof obj == 'object' && obj) {
                    return true;
                } else {
                    return false;
                }
            } catch (e) {
                console.log('error：' + str + '!!!' + e);
                return false;
            }
        }
        console.log('It is not a string!')
    },
    imeiScan2(e) {
        let that = this
        let qrcode = ''
        // wx.scanCode({
        //     success(res) {
        //         qrcode = res.result;
        //         if (!qrcode) return showMsg('扫描失败，请重新扫描')
        //         if (qrcode.length >= 15) {
        //             let reg = /^\d+$/.test(qrcode)
        //             if (reg) {
        //                 qrcode = qrcode.substring(0, 15);
        //                 that.setData({
        //                     deviceImei: qrcode,
        //                 })
        //                 that.getDeviceByImei(qrcode)
        //             } else {
        //                 qrcode = qrcode.substr(qrcode.indexOf(86), 15)
        //                 that.setData({
        //                     deviceImei: qrcode,
        //                 })
        //                 that.getDeviceByImei(qrcode)
        //             }
        //         } else {
        //             showMsg('扫描失败，请重新扫描')
        //             return
        //         }
        //     }
        // })
        wx.scanCode({
            success(res) {
                qrcode = res.result;
                if (!qrcode) return showMsg('扫描失败，请重新扫描')
                if (qrcode.length >= 3) {
                    if (that.isjson(qrcode)) {
                        const result = JSON.parse(qrcode);
                        // JSON字符格式
                        that.setData({
                            deviceImei: result.ID, //威视达康摄像机取值，后续看需求更改 lc
                        })
                        that.getDeviceByImei(qrcode)
                    } else {
                        // 非JSON格式
                        that.setData({
                            deviceImei: qrcode,
                        })
                        that.getDeviceByImei(qrcode)
                    }
                } else {
                    showMsg('扫描失败，请重新扫描')
                    return
                }
            }
        })
    },
    // 新增设备
    goAddDevice() {
        this.setData({
            showSpace: true
        })
    },
    // 点击关闭弹窗
    closeSpace() {
        this.setData({
            showSpace: false
        })
    },
    // 去设备详情
    goDeviceDetail(e) {
        let {
            item
        } = e.currentTarget.dataset
        let info = JSON.stringify(item)
        console.log(item);
        if (item.classMark == 'V380') {
            // 宏视
            wx.navigateTo({
                url: `/packageA/pages/index-inside-page/macrovision-camera/macrovision-camera?info=${info}`,
            })
            return;
        } else if (item.protocol == '4') {
            // 萤石云
            wx.navigateTo({
                url: `/packageA/pages/index-inside-page/live/live?info=${info}`,
            })
            // wx.navigateTo({
            //     url: `/pages/index-inside-page/device-camera2/device-camera2?info=${info}`,
            // })
            return;
        }
        wx.navigateTo({
            url: `/packageA/pages/index-inside-page/device-detailed/device-detailed?info=${info}`,
        })
        // wx.navigateTo({
        //     url: `/pages/index-inside-page/device-detail/device-detail?info=${info}`,
        // })
        // wx.navigateTo({
        //     url: `/packageA/pages/index-inside-page/macrovision-camera/macrovision-camera?info=${info}`,
        // })
        // return;
        // if (item.deviceType == 'Camera') {
        //     if (item.classMark == 'V380') {
        //         // 宏视
        //         wx.navigateTo({
        //             url: `/packageA/pages/index-inside-page/macrovision-camera/macrovision-camera?info=${info}`,
        //         })
        //         return;
        //     }
        //     if (item.deviceMac == "" && item.manufacturerId != '1660554046491635714')
        //         return showMsg('设备MAC地址为空')
        //     if (item.manufacturerId == '1660554046491635714') {
        //         // 萤石云
        //         wx.navigateTo({
        //             url: `/pages/index-inside-page/device-camera2/device-camera2?info=${info}`,
        //         })
        //     } else {
        //         // 视洞
        //         wx.navigateTo({
        //             url: `/pages/index-inside-page/device-camera/device-camera?info=${info}`,
        //         })
        //     }
        // } else {
        //     wx.navigateTo({
        //         url: `/packageA/pages/index-inside-page/device-detail/device-detail?info=${info}`,
        //     })
        // }
    },

    // 点击复制imei
    clickCopyImei(e) {
        let {
            imei
        } = e.currentTarget.dataset
        wx.setClipboardData({
            data: imei,
            success(res) {
                wx.getClipboardData({
                    success(res) {
                        showMsg(`设备编码已复制`)
                    }
                })
            }
        })
    },

    // 点击删除设备
    clickDelete(e) {
        let id = e.currentTarget.dataset.id
        console.log(e);
        Dialog.confirm({
                title: '温馨提示',
                message: '此操作将解绑该设备，是否继续？',
            })
            .then(async () => {
                const res = await reqDeviceUserunBind(id)
                if (res.code != 20000) return showMsg(res.message);
                this.getInitDataList()
                showMsg("解绑成功")
            })
            .catch(() => {});
    },
})